package com.hooya.fa.eu.biz.dao.manager;

import com.hooya.fa.eu.api.enums.CkEnum;
import com.hooya.fa.eu.api.enums.CountryEnum;
import com.hooya.fa.eu.api.vo.DictVO;
import com.hooya.fa.eu.biz.dao.entity.CkDict;
import com.hooya.integrated.common.core.exception.CommonException;
import com.hooya.integrated.common.core.util.RedisUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

import static com.hooya.fa.eu.api.constant.DictConstant.DICT_PREFIX;

/**
 * @Description 1
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2024/4/24
 * @Version 1.0.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class DictManager {

    public Map<String, List<String>> getFbaCkFdsMap(List<CkDict> dictList) {
        Map<String, List<String>> fbaFdsCkMap = dictList.stream().filter(l ->
                        CkEnum.FBA_CK_MAP.getName().equals(l.getName()))
                .collect(Collectors.groupingBy(
                        CkDict::getParamKey,
                        LinkedHashMap::new,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> list.stream()
                                        .sorted(Comparator.comparing(CkDict::getSort))
                                        .map(CkDict::getParamValue)
                                        .collect(Collectors.toList())
                        )
                ));
        Map<String, Object> res = new HashMap<>(fbaFdsCkMap);
        RedisUtils.hmset(DICT_PREFIX + CkEnum.FBA_CK_REVERSAL_MAP.getName(), res);
        return fbaFdsCkMap;
    }

	public Map<String, List<String>> getFbaCkFdsMapDaily(List<CkDict> dictList) {
		Map<String, List<String>> fbaFdsCkMap = dictList.stream().filter(l ->
						CkEnum.FBA_CK_MAP.getName().equals(l.getName()))
				.collect(Collectors.groupingBy(
						CkDict::getParamKey,
						LinkedHashMap::new,
						Collectors.collectingAndThen(
								Collectors.toList(),
								list -> list.stream()
										.sorted(Comparator.comparing(CkDict::getSort))
										.map(CkDict::getParamValue)
										.collect(Collectors.toList())
						)
				));
		// 修复类型转换问题，确保类型匹配
		Map<String, Object> res = new HashMap<>();
		fbaFdsCkMap.forEach((key, value) -> res.put(key, value));
		RedisUtils.hmset(DICT_PREFIX + CkEnum.FBA_CK_REVERSAL_MAP.getName(), res);
		return fbaFdsCkMap;
	}

    public List<String> getXsOtherCkList(List<CkDict> dictList) {
        return dealNormalList(dictList, CkEnum.XS_OTHER_LIST.getName());
    }

    public List<String> getRestockMarkList(List<CkDict> dictList) {
        return dealNormalList(dictList, CkEnum.RESTOCK_MARK_LIST.getName());
    }

    public Map<String, String> getAbnormalBelongsMap(List<CkDict> dictList) {
        return dealNormalMap(dictList, CkEnum.ABNORMAL_BELONGS_MAP.getName());
    }

    public List<String> getSfCkList(List<CkDict> dictList) {
        return dealNormalList(dictList, CkEnum.SF_CK_LIST.getName());
    }

    public Map<String, List<String>> getCountryCkMap(List<CkDict> dictList) {
        Map<String, List<String>> res = dictList.stream().filter(l ->
                        l.getName().equals(CkEnum.COUNTRY_CK_MAP.getName()))
                .collect(Collectors.groupingBy(
                        CkDict::getParamKey,
                        LinkedHashMap::new,
                        Collectors.mapping(
                                CkDict::getParamValue,
                                Collectors.toList()
                        )
                ));
        RedisUtils.hmset(DICT_PREFIX + CkEnum.COUNTRY_CK_MAP.getName(), new HashMap<>(res));
        return res;
    }

    public Map<String, String> getOeuOrderMap(List<CkDict> dictList) {
        return dealNormalMap(dictList, CkEnum.OEU_ORDER_MAP.getName());
    }

    public List<String> getFbaWlList(List<CkDict> dictList) {
        return dealNormalList(dictList, CkEnum.FBA_WL_LIST.getName());
    }

    public Map<String, String> getFbaCkMap(List<CkDict> dictList) {
        dictList = dictList.stream().filter(l -> l.getName().equals(CkEnum.FBA_CK_MAP.getName())).collect(Collectors.toList());
        Map<String, String> res = dictList.stream().collect(Collectors.toMap(CkDict::getParamValue, CkDict::getParamKey));
        RedisUtils.hmset(DICT_PREFIX + CkEnum.FBA_CK_MAP.getName(), new HashMap<>(res));
        return res;
//        return dealNormalMap(dictList, CkEnum.FBA_CK_MAP.getName());
    }

	public Map<String, Map<String, List<String>>> getFbaCkCostwayMap(List<CkDict> dictList) {
		Map<String, Map<String, List<String>>> res = dictList.stream()
				.filter(l -> l.getName().equals(CkEnum.FBA_CK_COSTWAY_MAP.getName()) &&
						l.getParentId() == -1)
				.collect(Collectors.toMap(
						CkDict::getParamKey,
						parent -> dictList.stream()
								.filter(child -> Objects.equals(child.getParentId(), parent.getId()))
								.collect(Collectors.collectingAndThen(
										Collectors.groupingBy(
												CkDict::getParamKey,
												LinkedHashMap::new, // 使用LinkedHashMap来保持插入顺序
												Collectors.collectingAndThen(
														Collectors.toList(),
														list -> list.stream()
																.sorted(Comparator.comparing(CkDict::getSort))
																.map(CkDict::getParamValue)
																.collect(Collectors.toList())
												)
										),
										// 对paramKey按照自定义顺序排序
										map -> {
											Map<String, List<String>> sortedMap = new LinkedHashMap<>();
											CountryEnum.getCountryList().forEach(key -> {
												if (map.containsKey(key)) {
													sortedMap.put(key, map.get(key));
												}
											});
											return sortedMap;
										}
								))
				));
		RedisUtils.hmset(DICT_PREFIX + CkEnum.FBA_CK_COSTWAY_MAP.getName(), new HashMap<>(res));
		return res;
	}

	public List<String> dealNormalList(List<CkDict> dictList, String name) {
        List<String> res = dictList.stream().filter(l -> l.getName().equals(name))
                .map(CkDict::getParamValue).collect(Collectors.toList());
        //缓存数据先删除(数据库同步)
        RedisUtils.del(DICT_PREFIX + name);
        for (String data : res) {
            RedisUtils.sSet(DICT_PREFIX + name, data);
        }
        return res;
    }

    public Map<String, String> dealNormalMap(List<CkDict> dictList, String name) {
        Map<String, String> res = dictList.stream().filter(l -> l.getName().equals(name))
                .collect(Collectors.toMap(CkDict::getParamKey, CkDict::getParamValue));
        RedisUtils.hmset(DICT_PREFIX + name, new HashMap<>(res));
        return res;
    }

    public void cacheDict(List<CkDict> dictList) {
        getFbaCkFdsMapDaily(dictList);
        getAbnormalBelongsMap(dictList);
        getCountryCkMap(dictList);
        getOeuOrderMap(dictList);
        getFbaCkCostwayMap(dictList);
        getXsOtherCkList(dictList);
        getRestockMarkList(dictList);
        getFbaWlList(dictList);
        getSfCkList(dictList);
        getFbaCkMap(dictList);
    }

    public DictVO dealNormalMap(List<DictVO> res, String key, String name, List<DictVO> child) {
        DictVO listVO = new DictVO();
        listVO.setParamKey(key);
        listVO.setName(name);
        listVO.setType(CkEnum.getTypeByName(name));
        listVO.setDesc(CkEnum.getDescByName(name));
        listVO.setChildren(child);
        listVO.setIsSystem(CkEnum.getSystemFlagByName(name));
        child.forEach(c -> c.setIsSystem(listVO.getIsSystem()));
        res.add(listVO);
        return listVO;
    }

    public void checkTypeParam(DictVO dict) {
        CommonException.throwExOnCondition(
                dict.getType().equals(1) && StringUtils.isBlank(dict.getParamValue()), "0_0",
                "列表值不能为空！");
    }

}
